<template>
	<view class="my-posts-page">
		<!-- 下拉刷新容器 -->
		<scroll-view scroll-y class="scroll-container" @scrolltolower="loadMore" :refresher-enabled="true"
			:refresher-triggered="refreshing" @refresherrefresh="onRefresh" @refresherrestore="onRestore">

			<!-- 骨架屏 -->
			<view class="skeleton-container" v-if="loading && posts.length === 0">
				<view class="skeleton-item" v-for="i in 3" :key="i">
					<view class="skeleton-content">
						<view class="skeleton-title skeleton-animate"></view>
						<view class="skeleton-meta">
							<view class="skeleton-text skeleton-animate"></view>
							<view class="skeleton-text skeleton-animate"></view>
						</view>
					</view>
				</view>
			</view>

			<!-- 帖子列表 -->
			<view class="posts-list" v-else-if="posts.length > 0">
				<view class="post-item" v-for="post in posts" :key="post.postId"
					@click="handlePostClick(post.postId)">
					<!-- 帖子信息 -->
					<view class="post-info">
						<view class="post-header">
							<up-tag 
								:text="post.subCategory" 
								plain 
								size="mini" 
								type="primary"
							/>
							<text class="post-time">{{ formatTime(post.createTime) }}</text>
						</view>
						<text class="post-title">{{ post.title }}</text>
						<text class="post-content">{{ post.content }}</text>
						<view class="post-meta">
							<view class="meta-item">
								<up-icon name="eye" size="12" color="#999999"></up-icon>
								<text class="meta-text">{{ post.viewCount }}</text>
							</view>
							<view class="meta-item">
								<up-icon name="chat" size="12" color="#999999"></up-icon>
								<text class="meta-text">{{ post.commentCount }}</text>
							</view>
							<view class="meta-item">
								<up-icon name="thumb-up" size="12" color="#999999"></up-icon>
								<text class="meta-text">{{ post.likeCount }}</text>
							</view>
						</view>
					</view>

					<!-- 封面图 -->
					<image v-if="post.image && post.image.length > 0" :src="post.image[0]" mode="aspectFill"
						class="post-cover" lazy-load></image>

					<!-- 操作按钮 -->
					<view class="action-btn" @click.stop="handleMoreAction(post)">
						<up-icon name="more-dot-fill" size="18" color="#999"></up-icon>
					</view>
				</view>

				<!-- 加载更多 -->
				<view class="load-more" v-if="hasMore">
					<up-loading-icon v-if="loadingMore" size="20" />
					<text v-else class="load-more-text">上拉加载更多</text>
				</view>
				<view class="no-more" v-else>
					<text class="no-more-text">没有更多了</text>
				</view>
			</view>

			<!-- 空状态 -->
			<view class="empty-state" v-else-if="!loading && posts.length === 0">
				<up-icon name="edit-pen" size="80" color="#cccccc"></up-icon>
				<text class="empty-text">还没有发布过帖子</text>
				<text class="empty-hint">快去发布你的第一篇帖子吧～</text>
				<up-button type="primary" size="small" @click="handleGoPublish" color="#36d399" class="go-btn">
					去发布
				</up-button>
			</view>
		</scroll-view>

		<!-- 操作菜单 -->
		<up-action-sheet 
			:show="showActionSheet" 
			:actions="actionList" 
			@close="showActionSheet = false"
			@select="handleActionSelect"
		></up-action-sheet>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		mockGetPosts
	} from '../../server/mock.js';
	import showToast from '../../utils/showToast.js';
	import {
		formatRelativeTime
	} from '../../utils/date.js';

	// 状态
	const loading = ref(true);
	const refreshing = ref(false);
	const loadingMore = ref(false);
	const hasMore = ref(true);
	const posts = ref([]);
	const pageNum = ref(1);
	const pageSize = ref(10);
	const showActionSheet = ref(false);
	const currentPost = ref(null);

	// 操作菜单列表
	const actionList = ref([
		{ name: '编辑', color: '#36d399' },
		{ name: '删除', color: '#ff4d4f' }
	]);

	/**
	 * 加载我的帖子列表
	 */
	const loadPosts = async () => {
		try {
			const userInfo = uni.getStorageSync('userInfo');
			if (!userInfo) {
				showToast('请先登录', 'none');
				setTimeout(() => {
					uni.navigateBack();
				}, 1000);
				return;
			}

			// 模拟获取当前用户的帖子
			const res = await mockGetPosts({
				pageNum: pageNum.value,
				pageSize: pageSize.value,
				userId: userInfo.userId // 筛选当前用户的帖子
			});

			if (res.code === 200) {
				const newPosts = res.data.list || [];

				if (pageNum.value === 1) {
					posts.value = newPosts;
				} else {
					posts.value = [...posts.value, ...newPosts];
				}

				hasMore.value = newPosts.length >= pageSize.value;
			} else {
				showToast(res.message || '加载失败', 'error');
			}
		} catch (error) {
			console.error('加载我的帖子失败:', error);
			showToast('网络错误', 'error');
		} finally {
			loading.value = false;
		}
	};

	/**
	 * 格式化时间
	 */
	const formatTime = (time) => {
		if (!time) return '';
		return formatRelativeTime(time);
	};

	/**
	 * 下拉刷新
	 */
	const onRefresh = async () => {
		refreshing.value = true;
		pageNum.value = 1;
		hasMore.value = true;

		try {
			await loadPosts();
		} finally {
			setTimeout(() => {
				refreshing.value = false;
			}, 300);
		}
	};

	/**
	 * 刷新恢复
	 */
	const onRestore = () => {
		refreshing.value = false;
	};

	/**
	 * 加载更多
	 */
	const loadMore = () => {
		if (!hasMore.value || loadingMore.value || loading.value) return;

		loadingMore.value = true;
		pageNum.value += 1;
		loadPosts().finally(() => {
			loadingMore.value = false;
		});
	};

	/**
	 * 点击帖子
	 */
	const handlePostClick = (postId) => {
		uni.navigateTo({
			url: `/pages/post/postInfo?postId=${postId}`
		});
	};

	/**
	 * 更多操作
	 */
	const handleMoreAction = (post) => {
		currentPost.value = post;
		showActionSheet.value = true;
	};

	/**
	 * 选择操作
	 */
	const handleActionSelect = (item) => {
		if (item.name === '编辑') {
			handleEdit();
		} else if (item.name === '删除') {
			handleDelete();
		}
		showActionSheet.value = false;
	};

	/**
	 * 编辑帖子
	 */
	const handleEdit = () => {
		if (!currentPost.value) return;
		
		showToast('编辑功能开发中', 'none');
		// TODO: 跳转到编辑页面
		// uni.navigateTo({
		// 	url: `/pages/post/edit?postId=${currentPost.value.postId}`
		// });
	};

	/**
	 * 删除帖子
	 */
	const handleDelete = () => {
		if (!currentPost.value) return;

		uni.showModal({
			title: '提示',
			content: '确定要删除这篇帖子吗？',
			success: async (modalRes) => {
				if (modalRes.confirm) {
					try {
						// TODO: 调用删除接口
						// const res = await mockDeletePost(currentPost.value.postId);
						
						// 模拟删除成功
						posts.value = posts.value.filter(p => p.postId !== currentPost.value.postId);
						showToast('删除成功', 'success');
					} catch (error) {
						console.error('删除失败:', error);
						showToast('删除失败', 'error');
					}
				}
			}
		});
	};

	/**
	 * 去发布
	 */
	const handleGoPublish = () => {
		uni.switchTab({
			url: '/pages/publish/publishSelect'
		});
	};

	// 页面加载
	onMounted(() => {
		loadPosts();
	});
</script>

<style lang="scss" scoped>
	.my-posts-page {
		min-height: 100vh;
		background-color: #f5f5f5;

		.scroll-container {
			height: 100vh;
			padding: 20rpx;
		}
	}

	// 骨架屏
	.skeleton-container {
		.skeleton-item {
			background-color: #ffffff;
			border-radius: 16rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;

			.skeleton-content {
				.skeleton-title {
					height: 36rpx;
					background-color: #f0f0f0;
					border-radius: 4rpx;
					margin-bottom: 20rpx;
					width: 80%;
				}

				.skeleton-meta {
					display: flex;
					gap: 20rpx;

					.skeleton-text {
						height: 24rpx;
						background-color: #f0f0f0;
						border-radius: 4rpx;
						flex: 1;
					}
				}
			}

			.skeleton-animate {
				animation: skeleton-loading 1.5s ease-in-out infinite;
				background: linear-gradient(90deg,
						#f0f0f0 25%,
						#e0e0e0 50%,
						#f0f0f0 75%);
				background-size: 200% 100%;
			}
		}
	}

	// 帖子列表
	.posts-list {
		.post-item {
			position: relative;
			display: flex;
			gap: 20rpx;
			background-color: #ffffff;
			border-radius: 16rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;

			.post-info {
				flex: 1;
				min-width: 0;

				.post-header {
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-bottom: 12rpx;

					.post-time {
						font-size: 20rpx;
						color: #999999;
					}
				}

				.post-title {
					display: block;
					font-size: 32rpx;
					font-weight: 500;
					color: #333333;
					margin-bottom: 12rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}

				.post-content {
					display: block;
					font-size: 26rpx;
					color: #666666;
					line-height: 1.5;
					margin-bottom: 16rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					word-break: break-all;
				}

				.post-meta {
					display: flex;
					gap: 30rpx;

					.meta-item {
						display: flex;
						align-items: center;
						gap: 8rpx;

						.meta-text {
							font-size: 22rpx;
							color: #999999;
						}
					}
				}
			}

			.post-cover {
				width: 180rpx;
				height: 180rpx;
				border-radius: 12rpx;
				flex-shrink: 0;
				background-color: #f0f0f0;
			}

			.action-btn {
				position: absolute;
				top: 30rpx;
				right: 30rpx;
				padding: 10rpx;
			}
		}
	}

	// 加载更多
	.load-more,
	.no-more {
		text-align: center;
		padding: 30rpx 0;

		.load-more-text,
		.no-more-text {
			font-size: 24rpx;
			color: #999999;
		}
	}

	// 空状态
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 200rpx 0;
		gap: 20rpx;

		.empty-text {
			font-size: 28rpx;
			color: #999999;
		}

		.empty-hint {
			font-size: 24rpx;
			color: #cccccc;
			margin-bottom: 20rpx;
		}

		.go-btn {
			width: 200rpx;
		}
	}

	// 骨架屏动画
	@keyframes skeleton-loading {
		0% {
			background-position: 200% 0;
		}

		100% {
			background-position: -200% 0;
		}
	}
</style>

